eval 'exec perl -wS $0 ${1+"$@"}'
 if 0;

use strict;
use warnings;
use POSIX qw(strftime);

use DBI();
use File::Basename;
use File::stat;
use Data::Dumper 'Dumper';

use IO::Socket;

# Following variable is used as a general file descriptor for all the 
# output of the current tool (the log file). Actually, this file will
# contain the copy of both the stdout and stderr channel.
my $G_LOG;

################################################################################
#
################################################################################
sub get_time
{
    my $separator=shift @_;
    my @timelist = @_;
    
    my $now_time="";
    
    if (! defined $separator)
    {
	$separator=":";
    }
    
    if (scalar @timelist<1)
    {
	@timelist=localtime();
    }
    
    $now_time = strftime("%H".$separator."%M".$separator."%S",@timelist);
    
    return $now_time;
}

################################################################################
#
################################################################################
sub get_date
{
    my $separator=shift @_;
    my @timelist = @_;
    
    my $now_date="";
    
    if (! defined $separator)
    {
	$separator="/";
    }
    
    if (scalar @timelist<1)
    {
	@timelist=localtime();
    }
    
    $now_date = POSIX::strftime("%Y".$separator."%m".$separator."%d",@timelist);
    
    return $now_date;
}

################################################################################
#
################################################################################
sub mylog
{
    if ($G_LOG)
    {
	print $G_LOG get_date()." ".get_time()." ".join("",@_);
    }
}

################################################################################
#
################################################################################
sub error
{
    print STDERR get_date()." ".get_time()." [ERROR] ",@_;
    mylog "[ERROR] ", @_;
}

################################################################################
#
################################################################################
sub warning
{
    print STDERR get_date()." ".get_time()." [WARNING] ",@_;
    mylog("[WARNING],",@_);
}

################################################################################
#
################################################################################
sub debug
{
    my $h_ref_param=shift @_;
    
    if (exists $h_ref_param->{DEBUG})
    {
	print STDOUT get_date()." ".get_time()." [DEBUG] ",@_;
	mylog("[DEBUG] ",@_);
    }
}

################################################################################
#
################################################################################
sub info
{
    print STDOUT get_date()." ".get_time()." [INFO] ",@_;
    mylog("[INFO] ",@_);
}

################################################################################
#
################################################################################
sub print_h_content
{
    my $h_ref_param=shift @_;
    
    debug $h_ref_param, "Printing Global Hash Content:\n";
    debug $h_ref_param, "######################################################\n";
    foreach my $thekey (keys %$h_ref_param)
    {
	debug $h_ref_param, $thekey." => ".$h_ref_param->{$thekey}."\n";
    }
    debug $h_ref_param, "######################################################\n";
}

################################################################################
#
################################################################################
sub db_connect
{
    my $h_ref_param=shift @_;

    my $dbh = DBI->connect("DBI:mysql:database=".$h_ref_param->{DBNAME}.";host=localhost",
                         $h_ref_param->{DBLOGIN}, $h_ref_param->{DBPASSWD},
                         #{'RaiseError' => 0});
			   {'RaiseError' => 0, 'AutoCommit' => 0});

    $h_ref_param->{DB}=$dbh;

    return (defined $dbh);
}

################################################################################
#
################################################################################
sub db_disconnect
{
    my $h_ref_param=shift @_;
    $h_ref_param->{DB}->disconnect();
}

################################################################################
#
################################################################################
sub slsecd_connect
{
    my $h_ref_param=shift @_;
    my $socket=shift @_;
    my $proto=shift @_;
    my $peeraddr=shift @_;
    my $peerport=shift @_;
    
    $$socket=IO::Socket::INET->new( Proto     => $$proto,
				      PeerAddr  => $$peeraddr,
				      PeerPort  => $$peerport
				      );
    unless ($$socket)
    {
	return 0;
    }
    return 1;
}

################################################################################
#
################################################################################
sub slsecd_disconnect
{
    my $h_ref_param=shift @_;
    my $socket=shift @_;
    
    close $$socket;
}

################################################################################
#
################################################################################
sub get_deciphered_data
{
    my $h_ref_param=shift @_;
    my $h_ref_enciphered_keys = shift @_;
    my $ref_deciphered_keys = shift @_;
    my $res;
    my $socket=0;
    my $proto="tcp";
    #my $peeraddr="172.24.61.137";
    my $peeraddr="127.0.0.1";
    my $peerport="30000";

    
    if (! slsecd_connect($h_ref_param,\$socket,\$proto,\$peeraddr,\$peerport))
    {
	error("Failed to connect to slsecd.\n");
	return 4;
    }
    
    foreach my $thekey (keys %$h_ref_enciphered_keys)
    {
	if ($h_ref_enciphered_keys->{$thekey}=~/KO/)
	{
	    #chop ($thekey);
	    #print "$thekey;KO;\n";
	    push(@$ref_deciphered_keys,"$thekey;KO;;;;;;");
	}
	else
	{
	    #print { $h_ref_param->{SOCKET} } "D;" .$thekey. ";" .$h_ref_enciphered_keys->{$thekey}. "\n";
	    print $socket "D;" .$thekey. ";" .$h_ref_enciphered_keys->{$thekey}. "\n";

	    $res = <$socket>;
	    #print $thekey."/".$res;
	    chomp($res);
	    push(@$ref_deciphered_keys,$res);
	}
    }

    #print { $h_ref_param->{SOCKET} } "Q\n";
    print $socket "Q\n";
    if (! slsecd_disconnect($h_ref_param,\$socket))
    {
	warning("Failed to disconnect from slsecd.\n");
    }
    
    return 1;
}

################################################################################
#
################################################################################
sub db_get_list
{
    my $h_ref_param=shift @_;
    my $select=shift @_;
    my $res=0;
    my $sth;
    my $field="";
    my @list=();
    $field="imei";

    $sth = $h_ref_param->{DB}->prepare("$select");
    $sth->execute();

    while ( ($field) = $sth->fetchrow_array() ) 
    {
	#chop($field);
	push(@list,$field);
    }
    #warn Dumper [@ref];
    return @list;
}

################################################################################
#
################################################################################
sub db_get_id
{
    my $h_ref_param=shift @_;
    my $select_count = shift @_;
    my $select = shift @_;
    my $field = shift @_;
    my $res=0;
    my $sth;

    #print "SELECT_COUNT: " .$select_count. "\n";
    #print "SELECT: " .$select. "\n";

    $sth = $h_ref_param->{DB}->prepare("$select_count");
    $sth->execute();
    my $ref = $sth->fetchrow_hashref();
    
    $sth->finish();
    
    if ($ref->{'count(*)'} != 0)
    {
	$sth = $h_ref_param->{DB}->prepare("$select");
	$sth->execute();
	$ref = $sth->fetchrow_hashref();
    
	$sth->finish();
	#return $ref->{'event_id'};
	return $ref->{$field};
    }

    return $ref->{'count(*)'}!=0;
}

################################################################################
#
################################################################################
sub db_update_request_status
{
    my $h_ref_param=shift @_;
    my $request=shift @_;
    my $status=shift @_;
    my $comment=shift @_;
    my $sth;
    my $closed_date="";

    $closed_date=get_date()." ".get_time();

    my $sql="update request set status='$status', comment='$comment', close_date='$closed_date' where request_id='$request';";    
    #print $sql;
    $sth = $h_ref_param->{DB}->prepare($sql);
    $sth->execute();

    return 1;
}

################################################################################
#
################################################################################
sub db_get_mail
{
    my $h_ref_param=shift @_;
    my $request = shift @_;
    my $res=0;
    my $sth;

    $sth = $h_ref_param->{DB}->prepare("SELECT count(*) FROM request a INNER JOIN system_user b ON a.owner = b.login WHERE request_id = '$request'");
    $sth->execute();
    my $ref = $sth->fetchrow_hashref();
    
    $sth->finish();
    
    if ($ref->{'count(*)'} != 0)
    {
	$sth = $h_ref_param->{DB}->prepare("SELECT * FROM request a INNER JOIN system_user b ON a.owner = b.login WHERE request_id = '$request'");
	$sth->execute();
	$ref = $sth->fetchrow_hashref();
    
	$sth->finish();
	return $ref->{'mail'};
    }

    return $ref->{'count(*)'}!=0;
}

################################################################################
#
################################################################################
sub get_db_encipherered_data
{
    my $h_ref_param=shift @_;
    my $ref_requestedimeilist=shift @_;
    my $h_ref_encipheredkeyslist=shift @_;
    my $res=0;
    my $sth;
    my $imei="";
    
    foreach $imei(@$ref_requestedimeilist)
    {
	#chop($imei);
	$sth = $h_ref_param->{DB}->prepare("select count(*) from imei where imei='$imei' and data!=0");
	$sth->execute();
	my $ref = $sth->fetchrow_hashref();
	$sth->finish();

	if ($ref->{'count(*)'} != 0)
	{
	    $sth = $h_ref_param->{DB}->prepare("select data from imei where imei='$imei' and data!=0");
	    $sth->execute();
	    $ref = $sth->fetchrow_hashref();
	    $sth->finish();
	    $$h_ref_encipheredkeyslist{$imei}=$ref->{'data'};
	}
	else
	{
	    $$h_ref_encipheredkeyslist{$imei}="KO";
	}
    }
    return 1;
}

################################################################################
#
################################################################################
sub db_update_requested_imei_status
{
    my $h_ref_param=shift @_;
    my $request=shift @_;
    my $id=0;
    my $sth;
    my @content=();
    my $file="/tmp/".$request.".txt";
    
    my $imei="";
    my $valid="";
    my $comment="";

    $request=~/.{8}1(.+)/;
    $id=$1;

    my $dbh = DBI->connect("DBI:mysql:database=simgen;host=localhost",
			   "root","Admin01ME!",
			   {'RaiseError' => 0, 'AutoCommit' => 0});
    
    open(FILE, "<$file");
    @content = <FILE>;

    foreach my $line (@content)
    {
	chomp($line);
	$imei="";
	$valid="";
	$comment="";
	($imei,$comment)=split(";",$line);
	#print "-> ".$imei. " -> ".$valid. " -> ".$comment."\n";
        # update imei 
	if($comment eq "KO")
	{
	    $sth =$h_ref_param->{DB}->prepare("update requested_imei set status='error',comment='KO' where request_id='$id' and imei='$imei';");
	}
	else 
	{
	    $sth =$h_ref_param->{DB}->prepare("update requested_imei set status='done',comment='OK' where request_id='$id' and imei='$imei' and status='yes';");
	}
	$sth->execute();
	
    }

    return 1;
}

################################################################################
#
################################################################################
sub update_output_file
{
    my $h_ref_param=shift @_;
    my $request=shift @_;
    my $request_id=0;
    my $sth;
    my $sth2;
    my @content=();
    my $file="/tmp/".$request.".txt";
    my $file2="/tmp/".$request."_2.txt";
    my $sql="";
    my $sql2="";
    my $imei="";
    my $comment="";
    my $field="";
    my @cc=();

    $request=~/.{8}1(.+)/;
    $request_id=$1;

    my $dbh = DBI->connect("DBI:mysql:database=simgen;host=localhost",
			   "root","Admin01ME!",
			   {'RaiseError' => 0, 'AutoCommit' => 0});
    
    open(FILE, "<$file");
    @content = <FILE>;
    
    #$sth =$h_ref_param->{DB}->prepare("select imei,customer_request_id from requested_imei where request_id='$id';");
    $sql="SELECT * FROM `requested_imei` AS a LEFT JOIN `customer_request` AS b ON a.customer_request_id = b.id LEFT JOIN `system_user` AS c ON b.requester_id=c.id where b.request_id='$request_id';";
    $sth =$h_ref_param->{DB}->prepare($sql);
    $sth->execute();

    while (my @data = $sth->fetchrow_array())
    {
	# $data[3] = imei 
        # $data[10] = mail date 
        # $data[11] = mail subject 
        # $data[16] = sender mail

	foreach my $line(@content)
	{
	    @cc=();
	    chomp($line);
	    $imei="";
	    $comment="";
	    ($imei,$comment)=split(";",$line);
	    
	    if ($imei eq $data[3])
	    {
                #getting CC
		$sql2="SELECT * FROM `cc_request` AS a LEFT JOIN `system_user` AS b ON a.cc_user_id = b.id WHERE `customer_request_id` ='$data[1]'";
		$sth2 =$h_ref_param->{DB}->prepare($sql2);
		$sth2->execute();
		while (my @data2 = $sth2->fetchrow_array())
		{
		    push(@cc,$data2[7]);
		}
		$sth2->finish();

		$field=$data[16].";".join(",",@cc).";".$data[11].";".$data[10].";".$data[3].";".$line;
		#print $field."\n";
		`echo '$field' >> $file2`;
	    }
	}
	
    }
    
    $sth->finish();

    close (FILE);    
    return 1;
}

################################################################################
#
################################################################################
sub process
{
    my $h_ref_param=shift @_;
    my $err=0;
    my $imei = "";
    my $imeisec = "";
    my $res=0;
    
    my $result = "";
    my $result2 = "";
    my $request_id="";
    my $inputfile="";
    my $outputfile="";
    my $badimeitmp="";
    my @badimeitmp=();
    my @fields=();

    print_h_content($h_ref_param);

    # Checking lock file existence first in order to avoid to run two same
    # instance of the tool in parallel.
    info "Checking lock file ... \n";
    if ( -f $h_ref_param->{LOCK_FILE})
    {
	info "Lock file exits! Aborting... \n";
	return 1;
    }
    
    info "Creating lock file... \n";
    `touch $h_ref_param->{LOCK_FILE}`;
    if ($? != 0)
    {
	error("Failed to create lock file >$h_ref_param->{LOCK_FILE}< \n");
	return 1;
    }
    
    if (! db_connect($h_ref_param))
    {
	error("Failed to connect to database.\n");
	#$res=3;
	#goto ENDPROCESS;
	return 3;
    }
    
    my @requestlist=();
    my %encipheredkeyslist=();
    my @requestedimeilist=();
    my @decipheredkeyslist=();
    my $request_owner_mail="";

    info "Listing new requests...\n";
    @requestlist = db_get_list($h_ref_param,"select request_id from request where status='saved'");
    
    if (scalar @requestlist == 0)
    {
	info "No new requests found.  \n";
    } 
    else 
    {
    
	foreach my $request(@requestlist)
	{
	    info "Processing request $request... \n";
	    
	    if ( -f "/tmp/$request.txt")
	    {
		`rm -f "/tmp/$request.txt"`;
	    }
	    if ( -f "/tmp/$request.tmp")
	    {
		`rm -f "/tmp/$request.tmp"`;
	    }
	    
	    info "Getting request ID...\n";
	    $request_id = db_get_id($h_ref_param,"SELECT count(*) FROM request WHERE request_id='$request';","SELECT * FROM request WHERE request_id='$request';","id");
	    if ($request_id eq 0)
	    {
		error("REQUEST ID not found in DB for request $request. \n");
		return 1;
	    }
	    #print "request: ".$request_id."\n";
	    
	    info "Getting requested imei...\n";
	    @requestedimeilist=();
	    #@requestedimeilist = db_get_list($h_ref_param,"select imei from requested_imei where request_id='$request_id' and status='yes'");
	    @requestedimeilist = db_get_list($h_ref_param,"select imei from requested_imei where request_id='$request_id' and status='yes'");
	    
	    if (scalar @requestedimeilist == 0)
	    {
		error "No imei found for request $request.  \n";
		info "Updating request status...  \n";
		if (! db_update_request_status($h_ref_param,$request,"error","No imei found."))
		{
		    error "Failed to update request status.  \n";
		}
		next;
	    } 
	    
	    info "Getting encipherered keys...\n";
	    %encipheredkeyslist=();
	    if (! get_db_encipherered_data($h_ref_param,\@requestedimeilist,\%encipheredkeyslist))
	    {
		error "Failed to get encipherered keys list for request $request.  \n";
		next;
	    }

	    if (%encipheredkeyslist eq 0)
	    {
		error "No enciphered keys found from db for request $request.  \n";
		next;
	    } 
	    #warn Dumper [%encipheredkeyslist];
	    
	    info "Deciphering data...\n";
	    @decipheredkeyslist=();

	    if (! get_deciphered_data($h_ref_param,\%encipheredkeyslist,\@decipheredkeyslist))
	    {
		error "Failed to get decipherered data for request $request.  \n";
		next;
	    }
	   
	    if (scalar @decipheredkeyslist == 0)
	    {
		error "Failed to get deciphered data for request $request.  \n";
		next;
	    } 	 
	    #warn Dumper [@decipheredkeyslist];
	    
	    open (FILE,">/tmp/$request.txt");
	    
	    foreach my $line (@decipheredkeyslist)
	    {
		print FILE $line. "\n";
	    }
	    close (FILE);

	    
            # add bad IMEI from intitial list to output file
	    $inputfile="/tmp/".$request."_validate.txt";
	    $outputfile="/tmp/".$request.".txt";
	    $badimeitmp="/tmp/".$request.".tmp";

	    `grep error $inputfile >> $badimeitmp`;
	    open (FILE,"</tmp/$request.tmp");
	    @badimeitmp=<FILE>;
	    foreach my $badline (@badimeitmp)
	    {
		@fields=split(";",$badline);
		my $newbadline=$fields[0].";".$fields[2].";;;;;;";
		#print $newbadline;
		`echo '$newbadline' >> $outputfile`;
	    }
	    close (FILE);

	    info("Getting mail of request owner... \n");
	    $request_owner_mail = db_get_mail($h_ref_param,$request);
	    if (! $request_owner_mail)
	    {
		error("Failed to get owner mail for request $request. \n");
		return 1;
	    }
	    debug $h_ref_param, "REQUEST_OWNER_MAIL: " .$request_owner_mail. "\n";

	    # update requested imei status
	    info "Updating IMEI status...\n";
	    if (! db_update_requested_imei_status($h_ref_param,$request))
	    {
		error "Failed to update requested imei status.  \n";
		next;
	    }    

	    # add original info to output file (requester, cc list, request title,request date)
	    info "Completing output file with initial request info...\n";
	    if (! update_output_file($h_ref_param,$request))
	    {
		error "Failed to complete request $request.  \n";
		next;
	    }    

	    # creation output file
	    info "Creating XLS file...\n";
	    `/data/scripts/buildXls.php $request`;
	    	    
	    # send mail with result
	    info "Sending mail...\n";
	    #`/data/scripts/sendmail.pl -f max.support\@tcl.com -t $request_owner_mail -s "[ Request #: $request ] Max >get_keys.pl< notification" /tmp/$request.txt`;
	    `/data/scripts/sendmail.php max.support\@tcl.com "[ Request #: $request ] Unlock codes request" /tmp/$request.xls $request_owner_mail`;

	    info "Updating request status...\n";

	    if (! db_update_request_status($h_ref_param,$request,"done","OK"))
	    {
		error "Failed to update request status.  \n";
		next;
	    }
	    
	} # foreach my $request(@requestlist)
	
    } # if (scalar @requestlist == 0)
    info "End of Process. \n";
    
    if (! db_disconnect($h_ref_param))
    {
	warning "Failed to disconnect from database.\n";
    }
    
    info "Deleting lock file... \n";
    `rm -f $h_ref_param->{LOCK_FILE}`;
    
    return $res;
}

################################################################################
#
################################################################################
sub print_version
{
  my $h_ref_param=shift @_;
  print $h_ref_param->{EXECUTABLE_NAME}." ".$h_ref_param->{VERSION}." ".$h_ref_param->{RELEASE_DATE}."\n";
}

################################################################################
#
################################################################################
sub parse_args
{
    my $h_ref_param=shift @_;
    
    my $arg="";
    my $err=0;
    
    while ($arg=shift @ARGV)
    {
	chomp($arg);
	if ( $arg =~ /^-/ )
	{
	    if ( ($arg =~ /^-h/) || ($arg =~ /^--help/))
	    {
		print_usage($h_ref_param);
		exit(0);
	    }
	    elsif ( ($arg =~ /^-d/) || ($arg =~ /^--debug/))
	    {
		$h_ref_param->{DEBUG}=1;
	    }
	    elsif ( ($arg =~ /^-v/) || ($arg =~ /^--version/))
	    {
		print_version();
		exit(0);
	    }
	    
	    elsif ( ($arg =~ /^-l/) || ($arg =~ /^--log/))
	    {
		$arg=shift @ARGV;
		$h_ref_param->{LOG}=$arg;
	    }

	    else
	    {
		error "Unexpected option >$arg<.\n";
		$err++;
		next;
	    } 
	}
	else
	{
	    
	    #<dbname>: Mandatory. Local database name to use <dbname> database.\n";
	    if (! exists $h_ref_param->{DBNAME})
	    {
		$h_ref_param->{DBNAME}=$arg;
	    }
	    #<dblogin>: Mandatory. Local database login to use <dbname> database.\n";
	    elsif (! exists $h_ref_param->{DBLOGIN})
	    {
		$h_ref_param->{DBLOGIN}=$arg;
	    }
	    #<dbpasswd>: Mandatory. Local database password to use <dbname> database.\n";
	    elsif (! exists $h_ref_param->{DBPASSWD})
	    {
		$h_ref_param->{DBPASSWD}=$arg;
	    }
	}
    }
    
    if (! exists $h_ref_param->{DBPASSWD})
    {
	error("Missing arguments.\n");
	$err++;
    }
    
    if ($err>0)
    {
	error "Aborting due to previous error(s). Use -h or --help for usage.\n";
	return 1;
    }
    
    return 0;
}
    
################################################################################
#
################################################################################
sub print_usage
  {
    my $h_ref_param=shift @_;

    print "USAGE: ".$h_ref_param->{EXECUTABLE_NAME}." [-h|--help] [-d|--debug] [-v|--version] [-l|--log <log file>] ...] <dbname> <dblogin> <dbpasswd>\n";
    print "\n";
    print "PURPOSE:\n";
    print "   Insert ciphered data into the database \n";
    print "\n";
    print "PARAMETERS DESCRIPTION:\n";
    print "\n";
    print "   <dbname>: Mandatory. Local database name to use <dbname> database.\n";
    print "\n";
    print "   <dblogin>: Mandatory. Local database login to use <dbname> database.\n";
    print "\n";
    print "   <dbpasswd>: Mandatory. Local database password to use <dbname> database.\n";
    print "\n";
    print "OPTIONS DESCRIPTION:\n";
    print "   [-h|--help]:\n";
    print "      Print this usage message and exit.\n";
    print "\n";
    print "   [-v|--version]:\n";
    print "      Print the version number and exit.\n";
    print "\n";
    print "   [-d|--debug]:\n";
    print "      Print excessive output to understand the processing.\n";
    print "\n";
    print "\n";
  }

################################################################################
#
################################################################################
sub open_log
{
    my $h_ref_param=shift @_;

    if (! open($G_LOG,">>".$h_ref_param->{LOG}))
    {
	warning "Cannot create log file ".$h_ref_param->{LOG}." in current directory.\n";

	$h_ref_param->{LOG}="/tmp/".$h_ref_param->{EXECUTABLE_NAME}.".log";

	if (! open($G_LOG,">".$h_ref_param->{LOG}))
	{
	    warning "Still cannot create alternative log file ".$h_ref_param->{LOG}.". No log will be performed.\n";
	    $G_LOG=0;
	}
    }
}

################################################################################
#
################################################################################
sub intro
  {
    my $h_ref_param=shift @_;
    my $err=0;
    my $date_for_file="";

    # Updating some global variables.

    $h_ref_param->{START_TIME}=get_date("-")." ".get_time(":");

    $date_for_file=get_date("-")."_".get_time("-");
    
    $h_ref_param->{VERSION}="0.4.1";
    $h_ref_param->{EXECUTABLE_NAME}="get_keys.pl";

    $h_ref_param->{LOG}=$h_ref_param->{EXECUTABLE_NAME}.".$date_for_file.log";

    $h_ref_param->{LOCK_FILE}="/tmp/".$h_ref_param->{EXECUTABLE_NAME}.".lock";
    
    $h_ref_param->{RELEASE_DATE}="2007/10/25";

    # Following instruction forces flushing for each output to STDOUT or STDERR.
    $|=1;

    return 0;
  }

################################################################################
#
################################################################################
sub outtro
{
    my $h_ref_param=shift @_;
    if ($G_LOG)
    {
	close($G_LOG);
    }

    return 0;
}

################################################################################
#
################################################################################
sub main
{
  # This hash list will be used to store input parameters and some other
  # usefull information.
  # The actual valable keys are:
  #   VERSION:           string: current version of the tool.
  #   START_TIME:        string: start time of the script in the form YY_MM_DD.HH.MM.SS
  #   EXECUTABLE_NAME:   string: name of the current script.
  #   LOG:               string: name of the log file.
  #   RELEASE_DATE:      string: date of current tool release in form: YYYY/MM/DD
  #   DEBUG:             boolean: if this key exists, then the current script is run in
  #                               debug mode.
  #
  my %params=();
  my $res;
  
  if (intro(\%params)!=0)
  {
      error "Error while executing intro... Aborting.\n";
      exit(1);
  }

  if (parse_args(\%params)!=0)
  {
      error "Error while parsing arguments... Aborting.\n";
      exit(2);
  }
  
  open_log(\%params);
  
  $res = process(\%params);
  #if ($res!=0)
  #{
      #error "Error while processing... Aborting.\n";
  #}

  if (outtro(\%params)!=0)
  {
      error "Error while executing outtro... Aborting.\n";
      exit(13);
  }

  exit($res);

}


################################################################################
#
################################################################################

main();
exit(0);

